package br.com.gestaofacil.autenticacao.api.service;

import javax.persistence.NoResultException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import br.com.gestaofacil.autenticacao.core.model.User;
import br.com.gestaofacil.dao.autenticacao.IAutenticacaoDAO;

@Component("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private IAutenticacaoDAO autenticacaoDao;

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		return findByUsername(username);
	}

	private User findByUsername(String username) {
		try {
			autenticacaoDao.findUsers();
			return autenticacaoDao.findUserByUserName(username);

		} catch (NoResultException e) {
			throw new UsernameNotFoundException("Usuario nao encontrado");
		}
	}

	public void setAutenticacaoDao(IAutenticacaoDAO autenticacaoDao) {
		this.autenticacaoDao = autenticacaoDao;
	}

}
